//
//  PrinterHelper.swift
//  SwiftBluetoothScanDemo1
//
//  Created by Caijinglong on 2017/9/11.
//

import Foundation
typealias Byte = UInt8

/// printer helper
///
/// single instance
class PrinterPresenter{
    
    static var shared:PrinterPresenter = PrinterPresenter()
    
    var helper : BluetoothHelper!
    
//    var devices = [Printer]()
    
    private init(){
        helper = BluetoothHelper.shared
    }
    
    var index = 0
    
    let DIVIDER = "-----------------------------------------------"
    let ESC: Byte = 27//换码
    let FS: Byte = 28//文本分隔符
    let GS: Byte = 29//组分隔符
    let DLE: Byte = 16//数据连接换码
    let EOT: Byte = 4//传输结束
    let ENQ: Byte = 5//询问字符
    let SP: Byte = 32//空格
    let HT: Byte = 9//横向列表
    let LF: Byte = 10//打印并换行（水平定位）
    let CR: Byte = 13//归位键
    let FF: Byte = 12//走纸控制（打印并回到标准模式（在页模式下）
    let CAN: Byte = 24//作废（页模式下取消打印数据 ）
    
//    
//    var printerViews = Dictionary<Int,PrinterView>()
//    
//    func registerView(view:PrinterView) -> Int {
//        let key = synchronizedResult(index) { () -> Int in
//            let result = index
//            index += 1
//            return result
//        }
//        printerViews[key] = view
//        return key
//    }
//    
//    func unregisterView(viewIndex key:Int){
//        if let index = printerViews.index(forKey: key){
//            printerViews.remove(at: index)
//        }
//    }
//    
//    var lastCount = 0
//    
//    func scan(){
//        sdk.scanPrinters { printer in
//            if let p = printer{
//                if(!self.devices.contains(p)){
//                    self.devices.append(p)
//                    self.updateViewScans(devices: self.devices)
//                }
//            }
//            
//            if(self.lastCount == self.devices.count){
//                self.sdk.stopScanPrinters()
//            }
//            
//            self.lastCount = self.devices.count
//            
//        }
//    }
//    
//    func updateViewScans(devices:[Printer]){
//        printerViews.forEach { (_: Int, view: PrinterView) in
//            view.updateView(devices: devices)
//        }
//    }
    
    func conn(deviceName:String){
        helper.startScan(name: deviceName)
    }
    
    func disconnect(){
        helper.disconnect()
    }
    
    func sendMsg(msg:String) -> PrinterPresenter{
        try? helper.writeText(text: msg)
        return self
    }
    
    func sendBytes(bytes:[Byte]) -> PrinterPresenter{
        try? helper.writeData(data: Data.bytesArray(byteArray: bytes))
        return self
    }
    
    func sendHex(int:Int) -> PrinterPresenter {
        return self.sendHexs(hexInt: int)
    }
    
    func sendHexs(hexInt ints:Int...) -> PrinterPresenter{
        var data = Data()
        ints.forEach { (int) in
            data.append(UInt8(int))
        }
        try? helper.writeData(data: data)
        return self
    }
    
    func sendBytes(bytes:Byte...) -> PrinterPresenter{
        
        return self
    }
    
    func alignLeft()-> PrinterPresenter{
        return sendBytes(bytes: ESC,97,0)
    }
    
    func alignCenter() -> PrinterPresenter {
        return sendBytes(bytes: ESC,97,1)
    }
    
    func alignRight() -> PrinterPresenter{
        return sendBytes(bytes: ESC,97,2)
    }
    
    func printDivider() -> PrinterPresenter {
        return sendMsg(msg: DIVIDER)
    }
    
    func setFontSize(size:Int)  -> PrinterPresenter{
        var realSize: Byte = 0
        switch (size) {
        case 1 :
            realSize = 0
        case 2 :
            realSize = 17
        case 3 :
            realSize = 34
        case 4 :
            realSize = 51
        case 5 :
            realSize = 68
        case 6 :
            realSize = 85
        case 7 :
            realSize = 102
        case 8 :
            realSize = 119
        default:
            realSize = 0
        }
        var result = [Byte]()
        result[0] = 29
        result[1] = 33
        result[2] = realSize
        return sendBytes(bytes: result)
    }
    
    func newLine(lines:Int = 1) -> PrinterPresenter{
        for _ in 0...lines - 1{
            _ = sendMsg(msg: "\n")
        }
        return self
    }
    
    /**
     * 选择加粗模式
     
     * @return
     */
    func boldOn() -> PrinterPresenter {
        var result = [Byte]()
        result[0] = ESC
        result[1] = 69
        result[2] = 0xF
        return sendBytes(bytes: result)
    }
    
    
    /**
     * 取消加粗模式
     
     * @return
     */
    func boldOff() -> PrinterPresenter {
        var result = [Byte]()
        result[0] = ESC
        result[1] = 69
        result[2] = 0xF
        return sendBytes(bytes: result)
    }
    
    func subTitle(_ title:String) -> PrinterPresenter{
        return alignCenter()
            //            .setFontSize(size: 2)
            //            .boldOn()
            //            .setFontSize(size: 1)
            .sendMsg(msg: title)
        //            .boldOff()
        //            .alignLeft()
    }
    
    func sendQrcode(qrcode:String) -> Self{
        
        return self
    }
}
